/*
 * Copyright 2019 xiaomaoguai.com All right reserved. This software is the
 * confidential and proprietary information of xiaomaoguai.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with xiaomaoguai.com.
 */

package com.xiaomaoguai.core.next.tddl.config;

import static com.xiaomaoguai.core.next.tddl.constants.TddlConstants.MULTI_CONFIG_PREFIX;

import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import com.alibaba.fastjson.JSON;

import app.myoss.cloud.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import lombok.extern.slf4j.Slf4j;

/**
 * TDDL 自动配置，支持多个数据库
 *
 * @author chenyao
 * @since 2018年7月15日 下午4:37:48
 */
@AutoConfigureBefore(MybatisAutoConfiguration.class)
@Slf4j
@EnableConfigurationProperties({ TddlMultiProperties.class })
@ConditionalOnProperty(prefix = MULTI_CONFIG_PREFIX, value = "enabled", matchIfMissing = false)
@Configuration
public class TddlMultiAutoConfiguration {
    /**
     * 初始化多个 TDDL 自动配置
     *
     * @param environment 环境变量属性
     * @return TDDL 自动扫描注册器
     */
    @Bean
    public TddlMultiScannerConfigurer tddlMultiScannerConfigurer(Environment environment) {
        Binder binder = Binder.get(environment);
        TddlMultiProperties properties = binder.bind(MULTI_CONFIG_PREFIX, TddlMultiProperties.class).get();
        if (log.isInfoEnabled()) {
            log.info("init multi TDDL auto configuration, properties: {}", JSON.toJSONString(properties));
        }
        TddlMultiScannerConfigurer multiScannerConfigurer = new TddlMultiScannerConfigurer();
        multiScannerConfigurer.setProperties(properties);
        return multiScannerConfigurer;
    }
}
